<template>
  <CompOperate
      :field="field"
      :designer="designer"
      :design-state="designState"
      :parent-list="parentList"
      :parent-widget="parentWidget"
      :sub-form-row-id="subFormRowId"
      :sub-form-row-index="subFormRowIndex"
      :sub-form-col-index="subFormColIndex"
      :index-of-parent-list="indexOfParentList"
      :display-style="field['options'].displayStyle"
  >
    <div class="scene-waiting-call-records-widget" :style="getStyle('head')">
      <div class="waiting-inside">
        <!--队列-->
        <div class="column queue departTitle">
          <template v-for="(item, index) in waitingPatientInfos">
            <div
                class="queue-item"
                :class="`queue-item-${index + 1}`"
                :key="index + widgetKey"
            >
              <div>
                <div class="dept-name">
                  <ScrollX
                  >{{
                      optionsInfo.titleType && item
                          ? item[optionsInfo.titleType]
                          : item?.treatmentRoomName || "\u00a0"
                    }}
                  </ScrollX>
                </div>
                <div class="current-patient">
                  <template
                      v-for="(itemInfo, ItemIndex) in currentPatientInfos(
                      item?.treatingPatient
                    )"
                  >
                    <div class="patient-name">
                      <ScrollX>
                        {{ itemInfo.patientName || "\u00a0" }}
                      </ScrollX>
                    </div>
                    <div class="orderNo" v-if="!!itemInfo?.orderNo">
                      <ScrollX>
                        {{ itemInfo?.orderNo || "\u00a0" }}
                      </ScrollX>
                    </div>
                  </template>
                </div>
              </div>
            </div>
          </template>
        </div>
        <!--候诊患者-->
        <div class="column waitList">
          <div class="wait-inside">
            <div class="header">
              <!-- {{ optionsInfo.content || '等候穿刺' }}: &nbsp;{{ waitingPatientNumber.length }}人 -->
              {{ optionsInfo.content || "等候穿刺" }}: &nbsp;{{
                waitPatientNumber
              }}人
            </div>
            <div class="list-area-wrap">
              <vue-seamless-scroll
                  class="scroll"
                  :ref="`scroll`"
                  :classOption="scrollOption"
                  :data="waitingPatientNumber"
                  v-if="true"
              >
                <div class="list-area">
                  <template v-for="item in waitingPatientSummaryInfos">
                    <div class="group-first">
                      <template v-for="itemInfo in item">
                        <div class="patient-info">
                          <div class="patient-info-inside">
                           <span class="patientName">
                            {{ itemInfo?.patientName || "\u00a0" }}</span>
                            <span
                                class="orderNo"
                                :class="{ 'orderNo-no': !itemInfo?.orderNo }"
                                v-if="!!itemInfo?.orderNo"
                            >
                            {{ itemInfo?.orderNo || "\u00a0" }}
                          </span>
                          </div>

                        </div>
                      </template>
                    </div>
                  </template>
                </div>
              </vue-seamless-scroll>
            </div>
          </div>
        </div>
      </div>
    </div>
  </CompOperate>
</template>

<script>
import {v4 as uuid} from "uuid";
import {pxToVw} from "@/utils/common";
import emitter from "@/utils/designer/emitter";
import vueSeamlessScroll from "vue-seamless-scroll";
import {buildParentApi} from "@/utils/designer/util";
import ScrollX from "@c/public/seamlessScroll/ScrollX.vue";
import ScrollEditX from "@c/public/seamlessScroll/ScrollEditX.vue";
import ScrollEditY from "@c/public/seamlessScroll/ScrollEditY.vue";
import mixin from "@sc/templateDetails/modules/homeMiddle/fieldMixin";
import CompOperate from "@c/public/form-designer/devType/modules/compOperate.vue";

let buildParent = buildParentApi();

export default {
  name: "scene-waiting-call-records-TwoDepart-widget",

  componentName: "FieldWidget", //必须固定为FieldWidget，用于接收父级组件的broadcast事件

  mixins: [emitter, mixin],

  props: {
    widget: Object,
    field: Object,
    parentWidget: Object,
    parentList: Array,
    indexOfParentList: Number,
    designer: Object,
    designState: {
      type: Boolean,
      default: false,
    },
    devType: {
      type: Boolean,
      default: false,
    },

    subFormRowIndex: {
      /* 子表单组件行索引，从0开始计数 */ type: Number,
      default: -1,
    },
    subFormColIndex: {
      /* 子表单组件列索引，从0开始计数 */ type: Number,
      default: -1,
    },
    subFormRowId: {
      /* 子表单组件行Id，唯一id且不可变 */ type: String,
      default: "",
    },

    headTitle: {
      type: String,
      default: "",
    },
    visibleTitle: {
      type: Boolean,
    },
    //prop传入的表单JSON配置
    parentApi: {
      type: Object,
      default: () => buildParentApi(),
    },
  },

  components: {
    ScrollEditY,
    ScrollX,
    ScrollEditX,
    CompOperate,
    vueSeamlessScroll,
  },

  data() {
    return {
      waitPatientNumber: 0,
      widgetKey: uuid(),
      optionsInfo: Object(),
    };
  },

  computed: {
    //生成唯一的字符串
    getOnlyId() {
      return function () {
        return uuid();
      };
    },

    // 模板的行内样式
    getStyle() {
      return function (val) {
        const self = this;
        let info = self.optionsInfo || Array();
        let Obj = Object();
        switch (val) {
          case "head":
            Reflect.set(Obj, "height", pxToVw(info.contentHeight));
            return Obj;
          case "list":
            Reflect.set(Obj, "height", pxToVw(info.contentHeight));
            return Obj;
          case "listItem":
            Reflect.set(Obj, "lineHeight", pxToVw(info.lineHeight));
            Reflect.set(Obj, "height", pxToVw(info.lineHeight));
            return Obj;
        }
      };
    },

    // 滚动相关配置
    scrollOption() {
      const {
        waitScrollNumber = 5,
        waitScrollStep = 1,
        waitScrollState = false,
      } = this.optionsInfo;
      return {
        hoverStop: true,
        direction: 1, // 0向下 1向上 2向左 3向右
        isSingleRemUnit: true,
        step: [1, 1.5, 2, 2.5, 3][waitScrollStep - 1], // 数值越大速度滚动越快
        limitMoveNum: waitScrollState ? waitScrollNumber : 999999, // 开始无缝滚动的数据量 this.dataList.length
      };
    },

    // 列表的队列的患者
    waitingPatientInfos() {
      let list = Array();
      let devType = this.devType;
      let {showRowNums} = this.optionsInfo;
      let WaitingPatientList = this.$store.getters["getWaitingPatientInfo"];
      if (devType) {
        list = WaitingPatientList.apiData;
      } else {
        list = WaitingPatientList.mockData;
      }
      // 不在线的 提出队伍
      list = list.filter(item => {
        if (item.onlineStatus !== '2') {
          return true
        }
        return false
      })
      // 右侧上屏，数组兑换
      if (list.length > showRowNums) {
        if (this.optionsInfo.changeLocation) {
          let twoData = list.slice(0, 2);
          const temp = twoData[0];
          twoData[0] = twoData[1];
          twoData[1] = temp;
          return twoData;
        }
        return list.slice(0, showRowNums);
      } else {
        let arr = new Array(showRowNums - list.length).fill({});
        if (this.optionsInfo.changeLocation) {
          let twoData = [...list, ...arr];
          const temp = twoData[0];
          twoData[0] = twoData[1];
          twoData[1] = temp;
          return twoData;
        }
        return [...list, ...arr];
      }
    },

    // 获取队列正在就诊患者--1位
    currentPatientInfos() {
      return function (row) {
        if (row?.length) {
          return row.slice(0, 1);
        } else {
          return [{}];
        }
      };
    },

    // 获取队列候诊患者并成二维数组
    waitingPatientSummaryInfos() {
      const self = this;
      let chunkOriginal = Array();
      let waitPatientLists = self.waitingPatientInfos;
      waitPatientLists = waitPatientLists.filter((obj) => {
        // 检查对象不是空对象
        if (Object.keys(obj).length > 0) {
          return true;
        }
        return false;
      });
      let summary = self.$lodash.map(waitPatientLists, "waitPatientList");
      // 将 正在就诊的提出来
      let treatingPatientList = self.$lodash.map(
          waitPatientLists,
          "treatingPatient"
      );
      while (treatingPatientList.some((v) => Array.isArray(v))) {
        treatingPatientList = [].concat(...treatingPatientList);
      }
      if (summary && summary.length >= 2 && this.optionsInfo.changeLocation) {
        const temp = summary[0];
        summary[0] = summary[1];
        summary[1] = temp;
      }
      let flattenArr = self.$lodash.flattenDeep(summary);
      let uniqByArr = self.$lodash.uniqBy(flattenArr, "queuingId");

      uniqByArr = uniqByArr.filter((item) => {
        // 处理可能为空和存在正在就诊的数据的情况
        for (let i = 0; i < treatingPatientList.length; i++) {
          if (
              item &&
              treatingPatientList[i] &&
              treatingPatientList[i].queuingId == item.queuingId
          ) {
            return false;
          }
        }
        if (item) {
          return true;
        }
        return false;
      });

      this.waitPatientNumber = uniqByArr.length;
      if (uniqByArr.length >= 8) {
        chunkOriginal = uniqByArr.slice(0, 8);
      } else {
        let arr = new Array(8 - uniqByArr.length).fill({});
        chunkOriginal = [...uniqByArr, ...arr];
      }

      return self.$lodash.chunk(chunkOriginal, 4);
    },

    // 获取候诊患者数量
    waitingPatientNumber() {
      const self = this;
      let waitingPatientInfos = self.waitingPatientSummaryInfos;
      let flattenArr = self.$lodash.flattenDeep(waitingPatientInfos);
      let filterArr = self.$lodash.reject(flattenArr, self.$lodash.isEmpty);
      return filterArr || [];
    },
  },

  mounted() {
    this.handleOnMounted();
  },

  methods: {
    // 等待候诊滚动结束
    handleScrollEnd(e, row) {
      const self = this;
      if (self.$refs[`scroll-${row.workerId}`]) {
        console.log("等待就诊滚动结束");
        self.$nextTick(() => {
          self.$refs[`scroll-${row.workerId}`][0] &&
          self.$refs[`scroll-${row.workerId}`][0].reset();
        });
      }
    },

    // 接收父组件传递过来的数据
    async executeMethod(key, data) {
      switch (key) {
          // 队列列表
        case "patientListInfo":
          this.widgetKey = uuid();
          let patientList = this.$lodash.cloneDeep(data);
          //buildParent.executeParentMethod('writeLog', JSON.stringify({sign: '模板-患者信息', key: key, data: data}));
          await this.$store.dispatch("setWaitingPatientInfo", patientList);
          break;
          // 呼叫患者列表
        case "patientRecordsListInfo":
          this.widgetKey = uuid();
          let patientRecordsList = this.$lodash.cloneDeep(data);
          await this.$store.dispatch(
              "setWaitingPatientBusinessInfo",
              patientRecordsList
          );
          break;
      }
    },
  },

  watch: {
    field: {
      handler: function (val) {
        this.widgetKey = uuid();
        let key = val.options.config;
        this.optionsInfo = val.options[key];
      },
      deep: true,
      immediate: true,
    },
  },

  destroyed() {
    this.unregisterFromRefList();
  },
};
</script>

<style lang="scss" scoped>
.scene-waiting-call-records-widget {
  background-color: transparent;
  color: #333;
  align-self: center;
  align-items: center;
  display: flex;
  flex-direction: column;
  height: 100%;
  min-height: 800px;
  box-sizing: border-box;
  margin: 20px 159px 10px 148px;
  overflow: hidden;
  backdrop-filter: blur(4px);

  .waiting-inside {
    width: 100%;
    display: flex;
    flex-direction: column;
    height: 100%;
    overflow: hidden;
    font-family: "sharkFitHealth", serif !important;

    .column {
      height: 100%;
      box-sizing: border-box;
      border-radius: 20px !important;
      font-size: 48px;
      flex-shrink: 0;
      overflow: hidden;

      &:last-child {
        margin-right: 0;
      }
    }

    .departTitle {
      height: 409px;
      margin-bottom: 34px;
    }

    .queue {
      display: flex;
      justify-content: space-between;
      flex-shrink: 0;

      .queue-item {
        width: 788px;
        display: flex;
        align-items: center;
        background: rgba(14, 182, 201, 1);
        overflow: hidden;
        border-radius: 30px;
        padding: 28px 0 44px 0;
        box-sizing: border-box;
        flex-direction: column;
        border: 10px solid rgba(255, 255, 255, 0.2);

        .patient-name {
          overflow: hidden;
        }

        .dept-name {
          width: 544px;
          height: 170px;
          font-size: 106px;
          color: #ffffff;
          text-align: center;
          box-sizing: border-box;

          :deep(.st-inner) {
            width: 100%;
            margin: 0;
          }
        }

        .current-patient {
          font-size: 86px;
          height: 166px;
          color: #14314b;
          text-align: center;
          width: 544px;
          border-radius: 24px;
          box-sizing: border-box;
          align-self: center;
          align-items: center;
          justify-content: center;
          display: inline-flex;
          background: rgba(255, 244, 159, 1);
        }

        .orderNo {
          overflow: hidden;
          color: #ffffff;
          padding: 14px 24px 4px 24px;
          font-size: 74px;
          line-height: 74px;
          background: #14314b;
          margin-left: 20px;
          display: inline-flex;
          border-radius: 14px;
        }
      }

      .queue-item-2 {
        background: #008b8e;
      }
    }

    //候诊
    .waitList {
      width: 100%;
      display: inline-flex;
      flex-direction: column;
      flex-grow: 2.2;
      flex-shrink: 0;
      align-self: start;
      min-width: 600px;
      height: calc(100% - 443px);

      .wait-inside {
        height: 100%;

        .header {
          width: 100%;
          height: 109px;
          overflow: hidden;
          display: flex;
          flex-direction: column;
          align-items: center;
          align-self: center;
          background: #0eb6c9;
          color: #ffffff;
          justify-content: center;
          font-size: 60px;
          border-radius: 24px;
        }

        .list-area-wrap {
          overflow: hidden;
          margin-top: 10px;
          height: calc(100% - 110px);

          .scroll {
            overflow: hidden;
            height: 100%;
            border-radius: 18px;

            :deep(> div) {
              height: auto;
            }
          }
        }

        .list-area {
          display: flex;
          height: calc(100%);
          flex-direction: column;
          overflow: hidden;

          .group-first {
            display: flex;
            background: white;
            margin-top: 12px;
            flex-grow: 1;
            border-radius: 30px;
            overflow: hidden;
            box-sizing: border-box;
            height: 109px !important;

            &:first-child {
              margin-top: 0;
            }

            &:last-child {
              margin-bottom: 10px;
            }

            .patient-info {
              flex: 1 0 calc(100% / 4);
              padding: 30px 0;
              font-size: 54px;
              line-height: 54px;
              color: #14314b;
              min-width: calc(100% / 4);
              max-width: calc(100% / 4);
              box-sizing: border-box;
              display: flex;
              justify-content: center;
              align-items: center;
              overflow: hidden;
              .patient-info-inside{
                padding: 0 24px;
                @include singleEllipsis(100%);
                overflow: visible;
              }
            }

            .orderNo {
              overflow: hidden;
              color: #ffffff;
              padding: 8px 18px 4px 18px;
              font-size: 44px;
              background: #14314b;
              border-radius: 14px;
              margin-left: 20px;
            }

            .orderNo-no {
              background: #ffffff;
            }
          }
        }
      }
    }
  }
}
</style>